package com.byzk.p2p.front.controller;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.byzk.p2p.admin.bank.dto.BankCard;
import com.byzk.p2p.admin.bank.service.BankCardService;
import com.byzk.p2p.admin.base.controller.BaseController;
import com.byzk.p2p.admin.base.util.BaseUtil;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.base.util.MD5;
import com.byzk.p2p.admin.base.util.RequestUtil;
import com.byzk.p2p.admin.base.util.SHA;
import com.byzk.p2p.admin.borrow.service.TenderService;
import com.byzk.p2p.admin.fuiou.config.Config;
import com.byzk.p2p.admin.fuiou.dto.TransferToFreezenDto;
import com.byzk.p2p.admin.fuiou.util.SecurityUtils;
import com.byzk.p2p.admin.fuiou.util.WebUtils;
import com.byzk.p2p.admin.fuiou.util.XmlUtils;
import com.byzk.p2p.admin.money.dto.FundRecord;
import com.byzk.p2p.admin.money.service.FundRecordService;
import com.byzk.p2p.admin.money.util.FundRecordType;
import com.byzk.p2p.admin.money.vo.AccountFundVo;
import com.byzk.p2p.admin.money.vo.FundDetailVo;
import com.byzk.p2p.admin.score.dto.ScoreRecord;
import com.byzk.p2p.admin.score.service.ScoreRecordService;
import com.byzk.p2p.admin.system.dto.Callback;
import com.byzk.p2p.admin.system.dto.MemberLevel;
import com.byzk.p2p.admin.system.service.CallbackService;
import com.byzk.p2p.admin.system.service.MemberService;
import com.byzk.p2p.admin.system.service.SMSService;
import com.byzk.p2p.admin.user.dto.InviteRef;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.admin.user.dto.UserAuth;
import com.byzk.p2p.admin.user.service.UserAccountService;
import com.byzk.p2p.admin.user.service.UserAuthService;
import com.byzk.p2p.admin.user.service.UserService;
import com.byzk.p2p.front.service.FrontUserService;
import com.byzk.p2p.front.session.UserSession;
import com.byzk.p2p.front.util.LoginDto;

/**
 * 注册，登录，忘记密码相关
 * @author suker.zhou
 *
 */
@Controller
@Scope("prototype")
public class FrontUserController extends BaseController implements Serializable{
	
	@Autowired
	private FrontUserService frontUserService;
	@Autowired
	private UserService userService;
	@Autowired
	private SMSService sMSService;
	@Autowired
	private UserAccountService accountService;
	@Autowired
	private TenderService tenderService;
	@Autowired
	private ScoreRecordService scoreService;
	@Autowired
	private BankCardService bankCardService;
	@Autowired
	private UserAuthService authService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private CallbackService callbackService;
	@Autowired
	private FundRecordService fundService;
	
	private static final long serialVersionUID = 1L;

	/**
	 * 跳转注册页面
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public ModelAndView register(Model model,@RequestParam(value="invitePhone",required=false) String invitePhone) throws Exception {
		/*if(StringUtils.isNotBlank(inviteCode)){
			model.addAttribute("inviteCode", inviteCode);
		}*/
		if(StringUtils.isNotBlank(invitePhone)){
			model.addAttribute("invitePhone", invitePhone);
		}
		
		return new ModelAndView("/front/register");
	}
	
	/**
	 * 检查用户手机号是否已注册
	 * @param phone 手机号
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/phone/check", method = RequestMethod.POST)
	public String checkPhone1(@RequestParam(value="phone",required=false) String phone) throws Exception {
		if(StringUtils.isNotBlank(phone)){
			User user = frontUserService.selectByNameOrPhone(phone);
			if (user!=null) {
				super.printJSON(new JsonMsg(1, "该手机号已被注册！"));
				return null;
			}			
		}
		super.printJSON(new JsonMsg(-1, "该手机号可用！"));
		return null;
	}
	
	/**
	 * 用户注册时验证码校验
	 * @param code
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/code/check", method = RequestMethod.POST)
	public String checkCode(@RequestParam String code) throws Exception {
		String session_code = (String) session.getAttribute("jcaptchaCode");
		if (code != null && session_code.equalsIgnoreCase(code)) {
			super.printJSON(new JsonMsg(-1, "验证码正确！"));
			return null;
		}
		super.printJSON(new JsonMsg(1, "验证码错误！"));
		return null;
	}
	
	/**
	 * 临时保存
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	/*@RequestMapping(value="/temp/save",method=RequestMethod.POST)
	public String tempSave(Model model,@ModelAttribute User user) throws Exception{
		session.setAttribute("temp_user", user);
		//sendRegisterSms(model,user);
		super.printJSON(new JsonMsg(-1, "短信已发送至您的手机，请注意查收！",user.getPhone()));
		return null;
	}*/

	@RequestMapping("/register/step")
	public ModelAndView step_two(Model model,@RequestParam String phone){
		model.addAttribute("phone", phone);
		return new ModelAndView("/front/step");
	}
	/**
	 * 发送第二步注册验证码
	 * 
	 * @param model
	 * @throws Exception
	 */
	@RequestMapping(value = "/register/sms/send", method = RequestMethod.POST)
	public void sendSms(Model model, @ModelAttribute User vo) throws Exception {
		//sendRegisterSms(model, vo);
	}
	
	/**
	 * 发送注册短信验证码
	 * @param model
	 * @param vo
	 * @throws Exception
	 */
	/*private void sendRegisterSms(Model model,User vo) throws Exception{
		if (vo == null || StringUtils.isBlank(vo.getPhone())) {
			printJSON(new JsonMsg(1, "手机号不能为空！"));
			return;
		}
		List<User> list = frontUserService.getByUser(vo);
		if (list.size() > 0) {
			printJSON(new JsonMsg(2, "该手机号已经存在！"));
			return;
		}
		int intCount = 0;
		intCount = new Random().nextInt(9999);
		if (intCount < 1000) {
			intCount += 1000;
		}
		String randomCode = "" + intCount;
		sMSService.sendCaptchaCodeSms(vo.getPhone(),randomCode,request.getRemoteAddr());
		session.setAttribute("temp_code", SHA.encryptPassword(vo.getPhone().toString()+randomCode));
	}*/
	
	/**
	 * 找回密码&注册发送验证码--new
	 * @param model
	 * @param captcha 图形验证码
	 * @param phone 手机号
	 * @throws Exception
	 */
	@RequestMapping(value = "/code/sendSms", method = RequestMethod.POST)
	public void SendSms(Model model, @RequestParam(value="phone",required=false)String phone,
			@RequestParam(value="captcha",required=false)String captcha,
			@RequestParam(value="type",required=false)String type) throws Exception {
		String session_code = (String) session.getAttribute("jcaptchaCode");
		if (captcha != null && session_code.equalsIgnoreCase(captcha)) {
			if("register".equals(type)) {
				JsonMsg jsonMsg = sendRegisterSms(phone);
				printJSON(jsonMsg);
				return;
			}else if("forget".equals(type)) {
				JsonMsg jsonMsg = sendForgetPwdSms(phone);
				System.out.println("-------------" + jsonMsg);
				printJSON(jsonMsg);
				return;
			}else {
				super.printJSON(new JsonMsg(2, "短信发送失败！"));
			}
		}else {
			super.printJSON(new JsonMsg(1, "验证码错误！"));
		}
	}
	
	/**
	 * 发送注册短信验证码 ---方法--new
	 * @param model
	 * @param vo
	 * @throws Exception
	 */
	private JsonMsg sendRegisterSms(String phone) throws Exception{
		if (StringUtils.isBlank(phone)) {
			return new JsonMsg(1, "手机号不能为空！");
		}
		User user = new User();
		user.setPhone(phone);
		List<User> list = frontUserService.getByUser(user);
		if (list != null && list.size() > 0) {
			return new JsonMsg(2, "该手机号已经存在！");
		}
		/*int ipCount = sMSService.countSendIp(request.getRemoteAddr(), "注册短信");
		int phoneCount = sMSService.countSendPhone(phone, "注册短信");
		if(ipCount > 20){
			return new JsonMsg(3, "频繁获取验证码，ip已被封停。请明天再试！");
		}
		if(phoneCount > 6){
			return new JsonMsg(3, "频繁获取验证码，手机号已被封停。请明天再试！");
		}*/
		int intCount = 0;
		intCount = new Random().nextInt(9999);
		if (intCount < 1000) {
			intCount += 1000;
		}
//		String randomCode = "" + intCount;
//		sMSService.sendCaptchaCodeSms(phone,randomCode,request.getRemoteAddr());
		String randomCode = "0000";
		Map<String,Object> smsModel = new HashMap<String, Object>();
		smsModel.put("enCode", SHA.encryptPassword(phone+randomCode));
		smsModel.put("sendTime", new Date().getTime());
		session.setAttribute("temp_code", smsModel);
//		return new JsonMsg(-1, "短信已发送至您的手机，请注意查收！");
		return new JsonMsg(-1, "测谁阶段验证码为0000!");
	}
	
	/**
	 * 发送找回密码短信验证码 ---方法--new
	 * @param model
	 * @param vo
	 * @throws Exception
	 */
	private JsonMsg sendForgetPwdSms(String phone) throws Exception{
		if (StringUtils.isBlank(phone)) {
			return new JsonMsg(1, "手机号不能为空！");
		}
		User user = new User();
		user.setPhone(phone);
		List<User> list = frontUserService.getByUser(user);
		if (list != null && list.size() <= 0) {
			return new JsonMsg(2, "该手机号未注册，请先注册！");
		}
		/*int ipCount = sMSService.countSendIp(request.getRemoteAddr(), "找回密码短信");
		int phoneCount = sMSService.countSendPhone(phone, "找回密码短信");
		if(ipCount > 20){
			return new JsonMsg(3, "频繁获取验证码，ip已被封停。请明天再试！");
		}
		if(phoneCount > 6){
			return new JsonMsg(3, "频繁获取验证码，手机号已被封停。请明天再试！");
		}*/
		int intCount = 0;
		intCount = new Random().nextInt(9999);
		if (intCount < 1000) {
			intCount += 1000;
		}
//		String randomCode = "" + intCount;
//		sMSService.sendForgetPwdSms(phone,randomCode,request.getRemoteAddr());
		String  randomCode="0000";	
		Map<String,Object> smsModel = new HashMap<String, Object>();
		smsModel.put("enCode", SHA.encryptPassword(phone+randomCode));
		smsModel.put("sendTime", new Date().getTime());
		session.setAttribute("temp_code", smsModel);
//		return new JsonMsg(-1, "短信已发送至您的手机，请注意查收！");
		return new JsonMsg(-1, "验证码统一0000！");
	}
	
	
	/**
	 * 手机验证码比较
	 * @param code
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/check/randomCode")
	public String checkSmsCode(@RequestParam("code") String code,
							   @RequestParam("phone") String phone) throws Exception{
		String randomCode=(String) session.getAttribute("randomCode");
		if(randomCode==null){
			super.printJSON(new JsonMsg(1, "请先获取验证码"));
			return null;			
		}else{
			if(!SHA.encryptPassword(phone+randomCode).equals(SHA.encryptPassword(phone+code))){
				super.printJSON(new JsonMsg(2, "验证码错误"));
				return null;
			}
		}
		super.printJSON(new JsonMsg(-1, "验证码正确"));
		return null;
	}

	/**
	 * 检测用户名是否重复
	 * @param username
	 * @throws Exception 
	 */
	@RequestMapping("/check/username")
	public void checkUsername(@RequestParam(value="username", required=false) String username) throws Exception {
		User userCheck = frontUserService.selectByNameOrPhone(username);
		if(userCheck != null) {
			super.printJSON(new JsonMsg(0, "用户名已存在"));
			return;
		}
		super.printJSON(new JsonMsg(-1, "用户名不存在"));
	}
	
	/**
	 * 资金管理
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/account/fund/info",method=RequestMethod.GET)
	public String fundPie() throws Exception{
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		if(user == null){
			return redirect("/login");
		}
		
		AccountFundVo temp=new AccountFundVo();
		UserAccount account=accountService.getByUserId(user.getId());
		temp.setBalance(account.getBalance());
		temp.setFreezen(account.getFreezen());
		FundDetailVo detail=tenderService.getFundDetailVo(user.getId());
		temp.setAwaitFund(detail.getAwaitFund());
		temp.setAwaitInterest(detail.getAwaitInterest());
		
		super.printJSON(new JsonMsg(-1, "操作成功",temp));
		return null;
	}
	
	/**
	 * 找回密码 ---new
	 */
	@RequestMapping(value="/forget/save", method = RequestMethod.POST)
	public void forgetInfo(Model model,HttpServletRequest request,
							@RequestParam(value="phone",required=false) String phone , 
							@RequestParam(value="code",required=false) String code,
							@RequestParam(value="captcha",required=false) String captcha,
							@RequestParam(value="password",required=false) String password) throws Exception {
		if(StringUtils.isBlank(password)){
			super.printJSON(new JsonMsg(0, "请输入密码"));
			return ;
		}
		if(StringUtils.isBlank(code)){
			super.printJSON(new JsonMsg(0, "请输入您收到的验证码"));
			return ;
		}
		if(StringUtils.isBlank(captcha)){
			super.printJSON(new JsonMsg(0, "请输入图形验证码"));
			return ;
		}
		String session_code = (String) session.getAttribute("jcaptchaCode");
		if (!session_code.equalsIgnoreCase(captcha)) {
			printJSON(new JsonMsg(6, "图形验证码错误"));
			return;
		}
		/** 短信验证码 **/
		@SuppressWarnings("unchecked")
		Map<String,Object> smsModel = (Map<String, Object>) session.getAttribute("temp_code");
		if(smsModel == null) {
			super.printJSON(new JsonMsg(2, "短信验证码已过期"));
			return ;
		}
		long sendTime = (Long) smsModel.get("sendTime");
		if((sendTime+30*60*1000) < new Date().getTime()) {//发送时间加30分钟 比 现在的时间还小  说明已过期
			super.printJSON(new JsonMsg(2, "短信验证码已过期"));
			return ;
		}
		if(!SHA.encryptPassword(phone+code).equals((String) smsModel.get("enCode"))){
			super.printJSON(new JsonMsg(2, "短信验证码错误"));
			return ;			
		}
		/** END **/
		User user = null;
		try {
			user = frontUserService.selectByNameOrPhone(phone);
		} catch (Exception e) {
			super.printJSON(new JsonMsg(5, "找回密码失败"));
			return;
		}
		user.setPassword(MD5.GetMD5Code(password));
		int item = frontUserService.saveOrUpdate(user);
		if(item > 0) {
			session.removeAttribute("temp_code");
			super.printJSON(new JsonMsg(-1, "找回密码成功"));
		}else {
			super.printJSON(new JsonMsg(5, "找回密码失败"));
		}
	}
	
	/**
	 * 用户注册---new
	 * 
	 * @param model
	 * @param vo
	 * @param code
	 * @throws Exception
	 */
	@RequestMapping(value="/register/save", method = RequestMethod.POST)
	public void registerInfo(Model model,HttpServletRequest request,
							@RequestParam(value="phone",required=false) String phone , 
							@RequestParam(value="code",required=false) String code,
							@RequestParam(value="agree",required=false) String agree,
							@RequestParam(value="captcha",required=false) String captcha,
							@RequestParam(value="username",required=false) String username,
							@RequestParam(value="password",required=false) String password,
							@RequestParam(value="inviteCode",required=false) String inviteCode) throws Exception {
		if(StringUtils.isBlank(agree)){
			super.printJSON(new JsonMsg(3, "请勾选《使用协议》"));
			return ;
		}
		if(StringUtils.isBlank(username)){
			super.printJSON(new JsonMsg(0, "请输入用户名"));
			return ;
		}
		if(StringUtils.isBlank(password)){
			super.printJSON(new JsonMsg(0, "请输入密码"));
			return ;
		}
		if(StringUtils.isBlank(code)){
			super.printJSON(new JsonMsg(0, "请输入您收到的验证码"));
			return ;
		}
		if(StringUtils.isBlank(captcha)){
			super.printJSON(new JsonMsg(0, "请输入图形验证码"));
			return ;
		}
		String session_code = (String) session.getAttribute("jcaptchaCode");
		if (!session_code.equalsIgnoreCase(captcha)) {
			printJSON(new JsonMsg(6, "图形验证码错误"));
			return;
		}
		User user = new User();
		user.setPhone(phone);
		List<User> list = frontUserService.getByUser(user);
		if (list != null && list.size() > 0) {
			super.printJSON(new JsonMsg(2, "该手机号已经存在！"));
			return;
		};
		/** 短信验证码 **/
		@SuppressWarnings("unchecked")
		Map<String,Object> smsModel = (Map<String, Object>) session.getAttribute("temp_code");
		if(smsModel == null) {
			super.printJSON(new JsonMsg(2, "短信验证码已过期"));
			return ;
		}
		long sendTime = (Long) smsModel.get("sendTime");
		if((sendTime+30*60*1000) < new Date().getTime()) {//发送时间加30分钟 比 现在的时间还小  说明已过期
			super.printJSON(new JsonMsg(2, "短信验证码已过期"));
			return ;
		}
		if(!SHA.encryptPassword(phone+code).equals((String) smsModel.get("enCode"))){
			super.printJSON(new JsonMsg(2, "短信验证码错误"));
			return ;			
		}
		/** END **/
		User userCheck = frontUserService.selectByNameOrPhone(username);
		if(userCheck != null) {
			super.printJSON(new JsonMsg(5, "用户名已存在"));
			return ;
		}
		//邀请用户
		User inviteUser = null;
		if(StringUtils.isNotBlank(inviteCode)) {//邀请码不为空
			inviteUser = userService.getUserByPhone(inviteCode);
			if(inviteUser == null) {
				super.printJSON(new JsonMsg(5, "邀请用户不存在，请填写正确的邀请码"));
				return;
			}
		}
		User vo = new User();
		vo.setUsername(username);
		vo.setInviteCode(phone);//设置邀请码-即手机号
		vo.setPhone(phone);
		vo.setPassword(MD5.GetMD5Code(password));
		vo.setRegIp(RequestUtil.getRemortIP(request));
		vo.setRegTime(new Date());
		vo.setLastIp(RequestUtil.getRemortIP(request));
		vo.setLastTime(new Date());
		vo.setStatus("N");
		vo.setIsnew("Y");
		vo.setTerminal("PC");
		vo.setCreateTime(new Date());
		vo.setIsSpecial("N");
		vo.setOldUser("N");
		vo.setLoginCount(1);//注册后记录登录次数初始为1
		int item = frontUserService.saveOrUpdate(vo);
		accountService.saveOrUpdate(new UserAccount(vo.getId()));
		/** 建立邀请关系 **/
		if(inviteUser != null){
			InviteRef inviteRef = new InviteRef();
			inviteRef.setUserId(vo.getId());
			inviteRef.setPid(inviteUser.getId());
			inviteRef.setTakeAward(0);
			inviteRef.setCreateTime(new Date());
			frontUserService.saveOrUpdateInviteRef(inviteRef);//添加邀请关系
		}
		if(item > 0) {
			session.removeAttribute("temp_code");
			super.printJSON(new JsonMsg(-1, "注册成功！",vo.getUsername()));
		}else {
			super.printJSON(new JsonMsg(4, "注册失败！",vo.getUsername()));
		}
	}

	/**
	 * 注册成功页面
	 */
	@RequestMapping(value = "/register/success", method = RequestMethod.GET)
	public ModelAndView registerSuccess(Model model){
		//User vo = (User) session.getAttribute("_user");
		//model.addAttribute("user", vo);
		//session.removeAttribute("temp_user");
		return new ModelAndView("/front/success");
	}

	/**
	 * 跳转至登录页
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public ModelAndView login(){
		return new ModelAndView("/front/login");
	}
	
	/**
	 * 登录提交
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String loginSubmit(@ModelAttribute LoginDto dto) throws Exception{
		if(StringUtils.isBlank(dto.getUsername())){
			super.printJSON(new JsonMsg(1, "请输入用户名！"));
			return null;
		}
		User user=frontUserService.selectByNameOrPhone(dto.getUsername());
		if(StringUtils.isBlank(dto.getPassword())){
			super.printJSON(new JsonMsg(2, "请输入密码！"));
			return null;			
		}
		if(user==null){
			super.printJSON(new JsonMsg(4, "该用户未注册！"));
			return null;
			
		}
		if ("Y".equals(user.getOldUser()) && "N".equals(user.getIsfristLogin())) {// 老用户首次登录系统
			frontUserService.updateOldUserPwd(MD5.GetMD5Code(dto.getPassword()), "Y",user.getId());
		}
		if (user.getPassword().equals(MD5.GetMD5Code(dto.getPassword()))|| user.getPassword().equals(MD5.GetMD5Code("&*()" + dto.getPassword() + "!@#$%^"))) {
			super.printJSON(new JsonMsg(-1, "操作成功！"));
			session.setAttribute("_user", user);
			return null;
		}
		super.printJSON(new JsonMsg(5, "密码错误！"));
		return null;
	}
	
	/**
	 * 登录提交
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/login/index",method=RequestMethod.POST)
	public String loginIndex(Model model,@ModelAttribute LoginDto dto) throws Exception{
		if(StringUtils.isBlank(dto.getUsername())){
			super.printJSON(new JsonMsg(1, "请输入用户名!"));
			return null;
		}
		
		
		User user=frontUserService.selectByNameOrPhone(dto.getUsername());
		session.setAttribute("_user", user);
		
		if(StringUtils.isBlank(dto.getPassword())){
			super.printJSON(new JsonMsg(2, "请输入密码!"));
			return null;
		}
		
		if(StringUtils.isBlank(dto.getCode())){
			super.printJSON(new JsonMsg(3, "请输入验证码!"));
			return null;
		}
		
		if(user==null){
			super.printJSON(new JsonMsg(4, "该用户未注册!"));
			return null;				
		}else{
			if(!user.getPassword().equals(SHA.encryptPassword(dto.getPassword()))){
				super.printJSON(new JsonMsg(5, "密码错误!"));
				return null;					
			}
		}
		String temp=(String) session.getAttribute("jcaptchaCode");
		if(!dto.getCode().equals(temp)){
			super.printJSON(new JsonMsg(6, "验证码错误!"));
			return null;					
		}
		super.printJSON(new JsonMsg(-1, "操作成功!"));
		return null;
	}
	
	@RequestMapping("/logout")
	public ModelAndView logout(){
		session.removeAttribute("_user");
		return new ModelAndView("/front/login");
	}

	/**
	 * 内部邀请码是否存在
	 * @param insideInviteCode 内部邀请码
	 * @return
	 */
	private List<User> checkInsideInviteCodeExsit(String insideInviteCode){
		return userService.getUserByInviteCode(insideInviteCode);
	}
	
	/**
	 * 生成邀请码
	 * @param code 邀请码
	 * @return 
	 */
	private String generateInviteCode(String code) {
		//存在邀请码，继续生成新的邀请码，否则直接返回手机后六位为自己的邀请码
		if(checkInviteCodeExsit(code) != null){
			int intCount = 0;
			intCount = (new Random()).nextInt(999);
			if (intCount < 100) {
				intCount += 100;
			}
			code=code+intCount;//inviteCode+3位数字随机码
			generateInviteCode(code);
		}
		return code;
	}
	
	/**
	 * 邀请码是否存在
	 * @param code
	 * @return
	 */
	private User checkInviteCodeExsit(String code){
		User user = frontUserService.getUserByInviteCode(code);
		return user;
	}
	
	@RequestMapping(value="/check/inviteCode",method=RequestMethod.POST)
	private void checkInviteCode(@RequestParam String InviteCode) throws Exception{
		List<User> userList=userService.getUserByInviteCode(InviteCode);
		if(userList.size()>0){
			printJSON(new JsonMsg(-1, "邀请码存在！"));
		}else{
			printJSON(new JsonMsg(1, "您输入的邀请码不存在！"));
		}
	}
	
	/**
	 * 签到抽奖
	 * @throws Exception 
	 */
	@RequestMapping("/draw")
	private void reward() throws Exception{
		User user = (User) session.getAttribute("_user");
		if(user==null){
			super.printJSON(new JsonMsg(1, "请先登录"));
			return;
		}
		UserAccount account=accountService.getByUserId(user.getId());
		MemberLevel level=memberService.getById(account.getLevel());
		int score=account.getScore();
		if(score<level.getScore()){
			super.printJSON(new JsonMsg(2, "积分余额不足"));
			return;			
		}
		
		List<ScoreRecord> listRecord=scoreService.selectByWay(user.getId(), "抽奖消耗积分");
		if(listRecord.size()>20){
			super.printJSON(new JsonMsg(2, "抽奖次数上限20次"));
			return;			
		}else{
			//签到抽奖
			int index=BaseUtil.lottery();
			int result=calc(index);
			Double amount=0.0;
			String remark = "";
			switch (result) {
			case 0:
				amount=1.0;
				remark="五等奖";
				break;
			case 1:
				amount=2.0;
				remark="四等奖";
				break;
			case 2:
				amount=8.0;
				remark="三等奖";
				break;
			case 3:
				amount=28.0;
				remark="二等奖";
				break;
			case 4:
				amount=88.0;
				remark="一等奖";
				break;
			}

			//转账
			addScoreAmount(user.getId(),amount,account.getLevel(),"积分抽奖-"+remark);
			
			super.printJSON(new JsonMsg(-1, "签到成功",result));
			return;
		}
	}

	public String addScoreAmount(Integer userId,Double amount,int levelId,String remark) {
		User user=userService.getById(userId);
		TransferToFreezenDto dto=new TransferToFreezenDto();
		dto.setMchnt_cd(Config.mchnt_cd);
		dto.setMchnt_txn_ssn(DateUtils.getFullFormat()+(new Random().nextInt(8999)+1000));
		dto.setOut_cust_no(Config.user_id);
		dto.setIn_cust_no(user.getPhone());
		dto.setContract_no("");
		dto.setRem("积分抽奖");
		dto.setAmt((int)(amount*100)+"");
		String inputStr=dto.regSignVal();
		dto.setSignature(SecurityUtils.sign(inputStr));
		
		MemberLevel level=memberService.getById(levelId);
		
		String backStr;
		try {
			backStr = WebUtils.sendHttp(Config.paltform_to_user_url,dto);
			System.out.println(backStr);
			
			Callback callback=new Callback("平台向用户转账",backStr,new Date());
			callbackService.saveOrUpdate(callback);
			
			String resp_code=XmlUtils.getXmlNodeValue(backStr, "resp_code");
			String mchnt_cd=XmlUtils.getXmlNodeValue(backStr, "mchnt_cd");
			if("0000".equals(resp_code) && Config.mchnt_cd.equals(mchnt_cd)){
				UserAccount account=accountService.getByUserId(userId);
				account.setBalance(account.getBalance()+amount);
				account.setTotalAmount(account.getTotalAmount()+amount);
				
				ScoreRecord record = new ScoreRecord();
				record.setUserId(user.getId());
				record.setOptType("out");
				record.setAmount(level.getScore());
				record.setWay("抽奖消耗积分");
				record.setCreateTime(new Date());
				record.setTerminal("PC");				
				scoreService.saveScoreRecord(record);
				
				account.setScore(account.getScore()-level.getScore());
				accountService.saveOrUpdate(account);
				
				FundRecord fund=new FundRecord();
				fund.setCode(BaseUtil.generateCode(BaseUtil.ZIJINLIUSHUI));
				fund.setCreateTime(new Date());
				fund.setRemark(remark);
				fund.setType(FundRecordType.Type.CHOUJIANGJIANGLI.index);
				fund.setUserId(userId);
				fund.setIncome(amount);
				fund.setExpend(0.0);
				fund.setTerminal("PC");
				fund.setFreezen(0.0);
				fund.setBalance(account.getBalance());

				int item = fundService.saveOrUpdate(fund);
				accountService.saveOrUpdate(account);
				System.out.println(item);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public Integer calc(Integer amount){
		HashMap<Integer, Integer> hashMap=new HashMap<Integer, Integer>();
		hashMap.put(0, 450);  //1元
		hashMap.put(1, 950);  //2元
		hashMap.put(2, 984);  //8元
		hashMap.put(3, 996);  //28元
		hashMap.put(4, 1000);  //88元		
		//hashMap.put(5, 1000); //888元
		
		for (int i = 0; i <=hashMap.size(); i++) {
			Integer value=hashMap.get(i);
			if(amount<=value){
				return i;
			}else{
				continue;
			}
		}
		return 4;
	}
	/**
	 * 第三方注册第一步-实名认证
	 * @throws Exception 
	 */
	@RequestMapping(value="/auth/nextOne",method = RequestMethod.POST)
	public void nextOne(@RequestParam(value="realName")String realName,
						@RequestParam(value="idCardNo")String idCardNo) throws Exception {
		User user = (User) session.getAttribute("_user");
		if(user == null) {
			super.redirect("/login");
			return;
		}		
		user = userService.getById(user.getId());

		UserAuth userAuthCheck = authService.getUserAuthByIdCard(idCardNo);
		if(userAuthCheck != null && !user.getId().equals(userAuthCheck.getUserId())){//身份证号已存在
			super.printJSON(new JsonMsg(2, "该身份证号已被认证！"));
			return;
		}
		/** 不使用实名接口 **/
		//添加真实姓名
		user.setRealname(realName);
		int item = userService.saveOrUpdate(user);

		//添加实名认证
		UserAuth userAuth = authService.getIdNo(user.getId());
		if(userAuth == null) {
			userAuth = new UserAuth();
		}
		userAuth.setUserId(user.getId());
		userAuth.setAuthName(idCardNo);
		userAuth.setAuthType("id5");
		userAuth.setAuthTime(new Date());
		userAuth.setCreateTime(new Date());
		item = authService.saveOrUpdateUserAuth(userAuth);
		if(item > 0){
			super.printJSON(new JsonMsg(-1, "实名认证成功！"));
			return;
		}else {
			super.printJSON(new JsonMsg(2, "实名认证失败！"));
			return;
		}
		/** End **/
		//每天验证3次
		/*List<AuthRecord> recordList=authService.selectByDate(user.getId(), DateUtils.formatTime(new Date()));
		if(recordList.size()<=99){
			AuthResult auth=IDCardAuth.validate(URLEncoder.encode(realName, "UTF-8"), idCardNo);
			AuthRecord record=new AuthRecord();
			record.setUserId(user.getId());
			record.setMsg(auth.getMsg());
			record.setName(realName);
			record.setNo(idCardNo);
			record.setCreateTime(new Date());
			if("0".equals(auth.getCode())){
				record.setResult("Y");
				
				//添加真实姓名
				user.setRealname(realName);
				int item = userService.saveOrUpdate(user);

				//添加实名认证
				UserAuth userAuth = new UserAuth();
				userAuth.setUserId(user.getId());
				userAuth.setAuthName(idCardNo);
				userAuth.setAuthType("id5");
				userAuth.setAuthTime(new Date());
				userAuth.setCreateTime(new Date());
				item = authService.saveOrUpdateUserAuth(userAuth);
				
				authService.saveOrUpdateAuthRecord(record);
				
				super.printJSON(new JsonMsg(-1, "实名认证成功！"));
				return;
			}else{
				record.setResult("N");
				authService.saveOrUpdateAuthRecord(record);
				super.printJSON(new JsonMsg(3, "姓名与身份证号码不匹配！"));
			}
			
		}else{
			super.printJSON(new JsonMsg(4, "您今天验证已超过3次,请明天再试！"));
			return;
		}*/
	}
	
	
	/**
	 * 第三方注册第二步-银行卡绑定
	 * @throws Exception 
	 */
	@RequestMapping("/auth/nextTwo")
	public void nextTwo(@RequestParam(value="cityCode")String cityCode,
			@RequestParam(value="bankCode")String bankCode,
			@RequestParam(value="cardNo")String cardNo) throws Exception {
		User user = (User) session.getAttribute("_user");
		if(user == null) {
			super.redirect("/login");
			return;
		}			
		user = userService.getById(user.getId());
		//删除用户曾经绑定的银行卡
		int i = bankCardService.deleteByUserId(user.getId());
		if(i < 0) {
			super.printJSON(new JsonMsg(2, "银行卡绑定失败！删除旧银行卡错误！"));
			return;
		}
//		if(bankCardCheck != null && bankCardCheck.getIsDelete() == 0 && (!user.getId().equals(bankCardCheck.getUserId()))) {//银行卡已存在
//			super.printJSON(new JsonMsg(1, "银行卡已存在！"));
//			return;
//		}
//		if(bankCardCheck != null && bankCardCheck.getIsDelete() == 0 && user.getId().equals(bankCardCheck.getUserId())) {
//			bankCard = bankCardCheck;
//		}else {
//			bankCard = new BankCard();
//		}
		//添加银行卡
		BankCard bankCard = new BankCard();
		bankCard.setUserId(user.getId());
		bankCard.setBankName(bankCode);
		bankCard.setCityCode(cityCode);
		bankCard.setCardNo(cardNo);
		bankCard.setTerminal("PC");
		bankCard.setIsDelete(0);
		bankCard.setCreateTime(new Date());
		int item = bankCardService.saveOrUpdate(bankCard);
		if(item <= 0) {
			super.printJSON(new JsonMsg(2, "银行卡绑定失败！保存或更新银行卡发生错误！"));
			return;
		}
		super.printJSON(new JsonMsg(-1, "银行卡绑定成功！"));
	}
	
	/**
	 * 第三方注册第二步-密码设置
	 * @throws Exception 
	 */
	@RequestMapping("/auth/nextThree")
	public void nextThree(@RequestParam(value="loginPassword")String loginPassword,
			@RequestParam(value="payPassword")String payPassword) throws Exception {
		User user = (User) session.getAttribute("_user");
		if(user == null) {
			super.redirect("/login");
			return;
		}		
		user = userService.getById(user.getId());
		user.setDealPassword(MD5.GetMD5Code(payPassword));
		user.setLoginPassword(MD5.GetMD5Code(loginPassword));
		//user.setFuionAccount("Y");
		int item = userService.saveOrUpdate(user);
		if(item <= 0) {
			super.printJSON(new JsonMsg(1, "设置密码失败！"));
			return;
		}
		super.printJSON(new JsonMsg(-1, "设置密码成功！"));
		return;
	}
	
	@RequestMapping(value="/binding/phone",method=RequestMethod.GET)
	public ModelAndView bindingView(){
		return new ModelAndView("/front/binding");
	}
	
	@RequestMapping(value="/binding/phone",method=RequestMethod.POST)
	public String bindingPhone(@RequestParam("phone") String phone,
							@RequestParam("captcha") String captcha,
							@RequestParam("code") String code){
		try {
			if(StringUtils.isBlank(captcha)){
				super.printJSON(new JsonMsg(0, "请输入图形验证码"));
				return null;
			}
			String session_code = (String) session.getAttribute("jcaptchaCode");
			if (!session_code.equalsIgnoreCase(captcha)) {
				printJSON(new JsonMsg(6, "图形验证码错误"));
				return null;
			}
			if (StringUtils.isBlank(phone)) {
				super.printJSON(new JsonMsg(1, "手机号不能为空"));
				return null;
			}else{
				User temp=userService.getUserByPhone(phone);
				if(temp!=null){
					super.printJSON(new JsonMsg(1, "该手机号已被绑定"));
					return null;
				}
			}
			/** 短信验证码 **/
			@SuppressWarnings("unchecked")
			Map<String,Object> smsModel = (Map<String, Object>) session.getAttribute("temp_code");
			if(smsModel == null) {
				super.printJSON(new JsonMsg(2, "短信验证码已过期"));
				return null;
			}
			long sendTime = (Long) smsModel.get("sendTime");
			if((sendTime+30*60*1000) < new Date().getTime()) {//发送时间加30分钟 比 现在的时间还小  说明已过期
				super.printJSON(new JsonMsg(2, "短信验证码已过期"));
				return null;
			}
			if(!SHA.encryptPassword(phone+code).equals((String) smsModel.get("enCode"))){
				super.printJSON(new JsonMsg(2, "短信验证码错误"));
				return null;			
			}
			/** END **/
			User user = (User) session.getAttribute("_user");
			user.setPhone(phone);
			userService.saveOrUpdate(user);
			
			//刷新session
			session.setAttribute("_user", user);
			super.printJSON(new JsonMsg(-1, "绑定手机号成功"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}	
}
